package game.module.hall.dao;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.HallServer;

public class OnlineCountCache {

	private static Logger logger = LoggerFactory.getLogger(OnlineCountCache.class);

	static class SingletonHolder {
		static OnlineCountCache instance = new OnlineCountCache();
	}

	public static OnlineCountCache getInstance() {
		return SingletonHolder.instance;
	}

	private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

	private PlayerOnlineCount playerOnlineCount = new PlayerOnlineCount();

	public void setOnlineCount(int ddzOnlineCount, int nnOnlineCount, int sssOnlineCount, int mjOnlineCount) {
		readWriteLock.writeLock().lock();
		playerOnlineCount.ddzOnlineCount = ddzOnlineCount;
		playerOnlineCount.nnOnlineCount = nnOnlineCount;
		playerOnlineCount.sssOnlineCount = sssOnlineCount;
		playerOnlineCount.mjOnlineCount = mjOnlineCount;
		readWriteLock.writeLock().unlock();
	}

	public void scheduleQueryOnlineCount() {
		HallServer.executorService.scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				logger.info("schedule query room online player count!");
				String rsLanHost = HallServer.getInstance().getServerConfig().getRsLanHost();
				int rsLanPort = HallServer.getInstance().getServerConfig().getRsLanPort();
				boolean reconnectRet = HallServer.getInstance().getLanClientManager().connect(rsLanHost, rsLanPort);
				if (reconnectRet) {
					HallServer.getInstance().getLanClientManager().queryPlayerCount2Rs(rsLanHost, rsLanPort);
				} else {
					logger.error("connect 2 roomServer error!rsLanHost={},rsLanPort={}", rsLanHost, rsLanPort);
				}
			}
		}, 30, 200, TimeUnit.SECONDS);
	}

	public void respSetPlayerOnlineCount(int[] oldOnlineCount) {
		readWriteLock.readLock().lock();
		oldOnlineCount[0] += playerOnlineCount.ddzOnlineCount;
		oldOnlineCount[1] += playerOnlineCount.nnOnlineCount;
		oldOnlineCount[2] += playerOnlineCount.sssOnlineCount;
		oldOnlineCount[3] += playerOnlineCount.mjOnlineCount;
		readWriteLock.readLock().unlock();
	}

	public static final class PlayerOnlineCount {
		public int ddzOnlineCount;
		public int nnOnlineCount;
		public int sssOnlineCount;
		public int mjOnlineCount;
	}

}
